import router from './router';
import store from './store';
import NProgress from 'nprogress'; // Progress 进度条
import 'nprogress/nprogress.css'; // Progress 进度条样式
import { Message } from 'element-ui';
import { getToken, setToken, removeViceToken, setSaaSId } from '@/utils/auth'; // 验权
import { getUrlPramas } from '@/utils/index';
import { $config } from 'vue-element-simple';

const whiteList = ['/login']; // 不重定向白名单
router.beforeEach((to, from, next) => {
  NProgress.start();
  // 企业微信扫码登录失败
  if (to.path === '/login' && window.location.href.indexOf('qyLoginErrMsg=') >= 0) {
    Message.error(getUrlPramas('qyLoginErrMsg'));
    NProgress.done();
    // location.replace('http://192.128.28.111:9528' + '#/login');
    location.replace($config['API_PATH'] + '#/login');
    return;
  }
  // 判断是否是SaaS登录
  if (window.location.href.indexOf('system=') >= 0) {
    const SaaSId = getUrlPramas('system');
    console.log('========SaaS登录=========');
    console.log('SaaSId: ' + SaaSId);
    store.commit('SET_SAASID', SaaSId);
    setSaaSId(SaaSId);
  }
  // 判断是否是SaaS登录
  if (window.location.href.indexOf('SaaSToken=') >= 0) {
    const SaaSToken = getUrlPramas('SaaSToken');
    const SaaSId = getUrlPramas('SaaSId');
    console.log('========SaaS登录=========');
    console.log('SaaSToken: ' + SaaSToken);
    console.log('SaaSId: ' + SaaSId);
    (async () => {
      await removeViceToken();
      await setToken(SaaSToken);
      await setSaaSId(SaaSId);
      await store.commit('SET_SAASID', SaaSId);
      await store.commit('SET_TOKEN', SaaSToken);
      // location.replace('http://localhost:9528/');
      location.replace($config['API_PATH'] + '/');
    })();
    return;
  }
  // 判断是否已经登录
  if (getToken()) {
    if (to.path === '/login') {
      next({path: '/'});
      NProgress.done();
      return;
    }
    // 更新用户信息,如需每次路由跳转都更新则写在当前位置,否则则写在if内
    store.dispatch('GetInfo').catch((res) => {
      console.log('============获取用户信息============')
      console.log('获取用户信息失败, ' + res.msg);
    })

    // 当没有侧边菜单时
    if (store.getters.roles.length === 0) {
      store.dispatch('GetMenu').then(res => {
        const menu = res.data;
        // 这里拼接插件菜单
        store.dispatch('GenerateRoutes', {menu}).then(() => { // 根据roles权限生成可访问的路由表
          router.addRoutes(store.getters.addRouters); // 动态添加可访问路由表
          next({...to, replace: true}); // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
          NProgress.done();
        })
      }).catch((err) => {
        store.dispatch('FedLogOut').then(() => {
          Message.error(err || 'Verification failed, please login again');
          next({path: '/'});
          NProgress.done();
        })
      })
      return;
    }
    next();
    return;
  }

  // 判断是否是扫码登录
  if (window.location.href.indexOf('code=') >= 0) {
    const code = getUrlPramas('code');
    store.dispatch('ScanCodeLogin', code).then(() => {
      next({path: '/homepage'});
      NProgress.done();
    }).catch((res) => {
      Message.error(res.msg);
    })
    return;
  }

  // 判断是否是自动登录
  if (window.location.href.indexOf('wsToken=') >= 0) {
    const wsToken = getUrlPramas('wsToken');
    const wsDomain = getUrlPramas('wsDomain');
    console.log('========自动登录=========');
    console.log('wsToken: ' + wsToken);
    console.log('wsDomain: ' + wsDomain);
    store.dispatch('autoLogin', { wsToken: wsToken, wsDomain: wsDomain }).then(() => {
      // next({ path: '/homepage' });
      location.replace($config.API_PATH + '/');
      // location.replace('http://172.16.61.226:9528' + '/');
    }).catch((res) => {
      Message.error(res.msg);
    })
    return;
  }

  // --
  if (window.location.href.indexOf('msg') >= 0) {
    const url = decodeURI(window.location.href);
    let msg = url.split('?')[1];
    msg = msg.substring(4, msg.indexOf('&'));
    Message.error(msg);
    next();
    NProgress.done();
    return;
  }

  // 属于白名单免验证
  if (whiteList.indexOf(to.path) !== -1) {
    next();
    NProgress.done();
    return;
  }

  next('/login');
  NProgress.done();
})

router.afterEach(() => {
  NProgress.done(); // 结束Progress
})
